<template>
  <div class="login">
    <el-card class="login-box">
      <template #header>
        <div class="w-full flex items-center">
          <img
            src="https://file.supore.cn/1752719870supore.png"
            alt=""
            class="w-[5rem] h-[3rem]"
          />
          <div class="ml-2">雄博眼视光</div>
          <!-- <div class="text-white">桌面软件</div> -->
        </div>
      </template>
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginFormRef"
        label-width="4rem"
        @keyup.enter="submitForm"
      >
        <el-form-item label="用户名" prop="username" class="login_form">
          <template #label>
            <div class="login_title">
              账&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号
            </div>
          </template>
          <el-input
            v-model.trim="loginForm.username"
            placeholder="请输入用户名"
            @input="searchOrganizationData"
          >
            <template #suffix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" class="login_form">
          <template #label>
            <div class="login_title">
              密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码
            </div>
          </template>
          <el-input
            v-model.trim="loginForm.password"
            placeholder="请输入密码"
            type="password"
            show-password
          >
            <template #suffix v-if="loginForm.password == ''">
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="归属门店"
          prop="organId"
          v-if="organList && organList.length > 0"
          class="login_form"
        >
          <template #label>
            <div class="login_title">
              门&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;店
            </div>
          </template>
          <el-select
            v-model.trim="loginForm.organId"
            placeholder="请选择归属门店"
            @change="changeOrganBtn"
            filterable
          >
            <el-option
              v-for="item in organList"
              :key="item.id"
              :label="item.organName"
              :value="item.organId"
            ></el-option>
            <template #empty> 未查询到门店 </template>
          </el-select>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha" class="login_form">
          <template #label>
            <div class="login_title">验&nbsp;证&nbsp;码</div>
          </template>
          <div class="w-full flex justify-between items-center">
            <el-input
              v-model.trim="loginForm.captcha"
              placeholder="请输入验证码"
              style="width: 60%"
            />
            <div class="w-[33%] h-[30px] bg-[#ccc] hover:cursor-pointer">
              <img
                v-if="picPath"
                :src="picPath"
                alt="请输入验证码"
                class="w-full h-full align-middle rounded-3xl"
                @click="loginVerify()"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="w-full">
            <el-button
              @click="submitForm"
              class="w-full h-[2rem] bg-[var(--theme-color)] text-white text-[0.8rem]"
              :loading="loading"
            >
              {{ loading ? "登 录 中 ..." : "登 录" }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useUserStore } from "@/pinia";
import { handleApiResponse } from "@/utils/request.js";

import {
  Login,
  GetCaptcha,
  GetUserOrganList,
} from "../../../wailsjs/go/api/AuthApi.js";

onMounted(() => {
  loginVerify();
});

const useStore = useUserStore();
const router = useRouter();

const loginFormRef = ref(null);
const loginForm = ref({
  username: "",
  password: "",
  captcha: "",
  captchaId: "",
  organClassificationId: null, // 归属门店id
  domValue: "storebms",
});

// 登录功能
const loading = ref(false);
const submitForm = () => {
  loginFormRef.value.validate((valid) => {
    if (!valid) return false;

    loading.value = true;

    Login(loginForm.value).then((res) => {
      if (res.code == 0) {
        // 登录成功后跳转到首页
        // useStore.updateUserInfo(res.data.user);
        router.push({ name: "home_page" });
        useStore.updateToken(res.data.token);

        setTimeout(() => {
          window.runtime.WindowMaximise(); // 最大化窗口
        }, 600);
      } else {
        loginVerify();
        loginForm.value.captcha = "";
        ElMessage.error(res.msg);
      }
      loading.value = false;
    });
  });
};

// 选择门店
const changeOrganBtn = () => {
  let found = organList.value.find(
    (item) => item.organId == loginForm.value.organId
  );
  loginForm.value.organClassificationId = found.organClassificationId;

  useStore.updateThemeTitle(found.organName);
};

// 归属机构
const organList = ref([]);
let timerId = ref(null);
const searchOrganizationData = () => {
  if (timerId.value != null) {
    clearTimeout(timerId.value);
  }

  timerId.value = setTimeout(() => {
    GetUserOrganList(loginForm.value.username).then((res) => {
      if (res.code == 0) {
        organList.value = res.data.list || [];
        if (res.data && res.data.list.length > 0) {
          loginForm.value.organId = organList.value[0].organId;
          loginForm.value.organClassificationId =
            organList.value[0].organClassificationId;

          useStore.updateThemeTitle(organList.value[0].organName);
        } else {
          organList.value = [];
          loginForm.value.organId = null;
          loginForm.value.organClassificationId = null;
        }
      }
    });
  }, 800);
};
searchOrganizationData();

// 验证码
const picPath = ref("");
const loginVerify = async () => {
  handleApiResponse(() => GetCaptcha()).then((res) => {
    if (!res) {
      return false;
    }

    picPath.value = res.data.picPath;
    loginForm.value.captchaId = res.data.captchaId;
  });
};

const rules = ref({
  username: [
    {
      required: true,
      message: "请输入用户名",
    },
    {
      min: 6, // 最小长度为3个字符
      message: "用户名长度不能小于6个字符",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
    },
    {
      min: 6,
      message: "密码长度不能小于6个字符",
    },
  ],
  captcha: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    },
  ],
  organId: [
    {
      required: true,
      message: "请选择机构",
    },
  ],
});
</script>

<style scoped lang="scss">
.login {
  transition: all 0.5s ease-in-out;
  @apply w-full h-screen flex justify-center items-center;
}
.login-box {
  @apply w-[25rem];
}
.login .el-form-item {
  @apply mb-5;
}

.login-box :deep(.el-card__header) {
  @apply py-[0.5rem];
}

.login_form:focus-within {
  background-color: #f0eeee !important;

  // :deep(.el-input__wrapper) {
  //   box-shadow: 0 0 0 1px #ccc inset !important;
  // }
  // :deep(.el-select__wrapper) {
  //   box-shadow: 0 0 0 1px #ccc inset !important;
  // }
}

.login_title {
  color: #c0b4b4;
  // @apply text-[#ccc]
}
</style>